<?php

namespace Admin;

use AdminController;
use Config;
use DB;
use Input;
use Lang;
use Redirect;
use Sentry;
use Str;
use Validator;
use View;
use Cache;
use MyModel;
use Paginator;
use Jinput;
use Question;
use Category;
use Dictionary;

class DictionariesController extends AdminController {

    public function __construct() {
        $this->beforeFilter('auth');
    }

    public function getIndex() {
        // $category = Category::All()->toArray(); 
        // print_r($category); exit();
        $data['appends']['status'] = Jinput::get('status', '');
        $data['appends']['category'] = Jinput::get('category', -1);
        $myModel = new \MyModel();
        if ($data['appends']['category'] >= 0)
            $arrParams['conditions'][] = array('field' => 'dictionaries.category_id', 'opr' => '=', 'value' => $data['appends']['category']);
        if ($data['appends']['status'] != "")
            $arrParams['conditions'][] = array('field' => 'dictionaries.status', 'opr' => '=', 'value' => $data['appends']['status']);
        $arrParams['left_joins'][] = array('table' => 'categories', 'pk' => 'categories.id', 'fk' => 'category_id');
        $arrParams['paginate']['appends'] = $data['appends'];
        $arrParams['paginate']['nums'] = 10;
        $arrParams['selects'] = array('dictionaries.id', 'dictionaries.title', 'dictionaries.status', 'dictionaries.category_id', 'dictionaries.created_at', 'categories.title as category_title');
        $data['dictionaries'] = $myModel->listItems('Dictionary', $arrParams);
        $data['categories'] = \Category::
                where('type', '=', 'dictionary')
                ->lists('title', 'id');

        return View::make('backend/dictionaries/index', compact('data'));
    }

    public function getEdit($id) {
//         if (!Sentry::getUser()->hasAnyAccess(['question', 'question.edit']))
//            return View::make('backend/notallow');
        if (is_null($data['dictionary'] = Dictionary::find($id)))
            return Redirect::route('dictionaries')->with('error', 'Nội dung không tồn lại');
        $myModel = new \MyModel();

        $data['categories'] = \Category::
                where('type', '=', 'dictionary')
                ->lists('title', 'id');
        $data['status']['published'] = "Hiển thị";
        $data['status']['hidden'] = "Không hiển thị";
        $data['status']['request'] = "Được yêu cầu";

        return View::make('backend/dictionaries/edit', array("data" => $data));
    }

    public function getDelete($id) {
//        if (!Sentry::getUser()->hasAnyAccess(['question', 'question.delete']))
//            return View::make('backend/notallow');
        if (is_null($dictionary = \Dictionary::find($id)))
            return Redirect::to('admin/dictionaries')->with('error', '');
        try {
            $dictionary->delete();
            return Redirect::to('admin/dictionaries');
        } catch (Exception $ex) {
            return Redirect::to('delete/dictionary', $id)->with('error', $ex);
        }
    }

    /**
     *
     */
    public function postEdit($id) {
        $data = Input::get('data');
        $rules = array('title' => 'required');
        $validation = Validator::make($data['Dictionary'], $rules);
        if ($validation->fails()) {
            return Redirect::back()->withInput()->withErrors($validation);
        }
        $mymodel = new \MyModel();

        $question = $mymodel->saveItem('Dictionary', $data['Dictionary'], array('return' => 'class'));

        return Redirect::route('dictionaries', $id)->with('success', 'từ điển đã được lưu');
    }

    public function getCategories() {
        //   print_r(Category::where('type','=','dictionary')->select('title')->get()->toArray()); exit();
        $data['appends']['word'] = Jinput::get('word', '');
        $myModel = new \MyModel();
//        $data['categories'] = Category::where('type', '=', 'dictionary')
//                        ->where('title', 'like', '%' . $data['appends']['word'] . '%')->paginate(1);
        if ($data['appends']['word'] != "")
            $arrParams['conditions'][] = array('field' => 'title', 'opr' => 'like', 'value' => '%' . $data['appends']['word'] . '%');
        $arrParams['conditions'][] = array('field' => 'type', 'opr' => '=', 'value' => 'dictionary');
        $arrParams['paginate']['appends'] = $data['appends'];
        $arrParams['paginate']['nums'] = 15;
        $arrParams['paginate']['appends'] = $data['appends'];
        $data['categories'] = $myModel->listItems('Category', $arrParams);

        return View::make('backend/dictionaries/categories', compact('data'));
    }

    //Danh mục từ điển
    public function getCreateCategory() {

        $data['categories'] = \Category::
                where('type', '=', 'dictionary')
                ->lists('title', 'id');

        $data['categories'][0] = "Danh mục gốc";

        $data['status']['on'] = "Hiển thị";
        $data['status']['off'] = "Không hiển thị";
        return View::make('backend/dictionaries/createcategory', compact('data'));
    }

    public function postCreateCategory() {
        $data = Input::get('data');
        $condition = "dictionary";
        $test = \Category::where('title', '=', $data['Category']['title'])->where('type', '=', 'dictionary')->count();
        if ($test > 0) {
            return Redirect::back()->with('error_create_category','Tiêu đề đã tồn tại');
        }
        $category = new Category;
        $category->title = $data['Category']['title'];
        $category->parent_id = $data['Category']['category_id'];
        $category->type = "dictionary";
        $category->status = "on";
        try {
            $category->save();
        } catch (Exception $ex) {

            return Redirect::back()->withInput()->withErrors($ex);
        }

        return Redirect::to('admin/dictionaries/categories');
    }

    public function getDeleteCategory($id) {
        if (is_null($category = Category::find($id)))
            return Redirect::to('admin/dictionaries/categories')->with('error', '');
        try {
            foreach ($category->Childs as $child) {
                $child->parent_id = 0;
                $child->save();
            }
            foreach (Dictionary::where('category_id', '=', $id)->get() as $dictionary) {
                $dictionary->category_id = 0;
                $dictionary->save();
            }
            $category->delete();
            return Redirect::route('dictionaries/categories');
        } catch (Exception $ex) {
            return Redirect::route('dictionaries/categories')->with('error', $ex);
        }
    }

    public function getEditCategory($id) {
        if (is_null($data['category'] = Category::find($id)))
            return Redirect::route('dictionaries/categories')->with('error', 'Nội dung không tồn lại');

        $data['categories'] = Category::where('type', '=', 'dictionary')
                ->where('id', '<>', $id)
                ->lists('title', 'id');

        $data['status']['on'] = "Hiển thị";
        $data['status']['off'] = "Không hiển thị";

        return View::make('backend/dictionaries/editcategory', compact('data'));
    }

    public function postEditCategory($id) {
        $data = Input::get('data');
        $rules = array('title' => 'required');
        $validation = Validator::make($data['Category'], $rules);
        if ($validation->fails()) {
            return Redirect::back()->withInput()->withErrors($validation);
        }
        $mymodel = new MyModel();
        $category = $mymodel->saveItem('Category', $data['Category'], array('return' => 'class'));
        $key = 'list_categories_root' . date('d-m-Y');
        if (Cache::has($key)) {
            $list = Cache::forget($key);
        }
        return Redirect::route('dictionaries/categories', $id)->with('success', 'danh mục đã được lưu');
    }

}
